const jsZip = require('jszip')

module.exports = class SourceMapHandleV4 {
  constructor({customHandlerAdapter}) {
    this.customHandlerAdapter = customHandlerAdapter
  }

  apply(compiler) {
    compiler.hooks.emit.tapAsync('sourceMapHandle', (compilation, cb) => {
      const zip = new jsZip()
      compilation.getAssets().forEach((asset) => {
        if (asset.name.endsWith('.js.map')) {
          zip.file(asset.name, asset.source.source())
          // compilation.deleteAsset(asset.name)
          delete compilation.assets[asset.name]
        }
      })
      zip.generateAsync({ type: 'nodebuffer' }).then(content => {
        this.customHandlerAdapter.handle(content).finally(cb)
      })
    })
  }
}